
/**
 * 加法 add(0.123 , 1.4567 , 10.56789)
 * @param  {...any} val
 * @returns
 */
export function add (...val) {
  let sum = 0
  const maxDecimalLength = getMaxDecimalLength(...val)
  val.forEach((x, index) => {
    // 所有数值转为整数计算
    sum += Math.round(x * Math.pow(10, maxDecimalLength))
  })
  return sum / Math.pow(10, maxDecimalLength)
}

/**
 * 减法 subtract(0.123 , 1.4567 , 10.56789)
 * @param  {...any} val
 * @returns
*/
export function subtract (...val) {
  let sum = 0
  const maxDecimalLength = getMaxDecimalLength(...val)
  val.forEach((x, index) => {
    const nurVal = Math.round(x * Math.pow(10, maxDecimalLength))
    if (index === 0) {
      sum = nurVal
    } else {
      sum -= nurVal
    }
  })
  return sum / Math.pow(10, maxDecimalLength)
}

/**
 * 乘法 multiply(0.123 , 1.4567 , 10.56789)
 * @param  {...any} val
 * @returns
 */
export function multiply (...val) {
  let sum
  let decimalLengthSum = 0
  val.forEach((x, index) => {
    // 获取当前小数位长度
    const decimalLength = getMaxDecimalLength(x)
    // 将当前数变为整数
    const nurVal = Math.round(x * Math.pow(10, decimalLength))
    decimalLengthSum += decimalLength
    if (index === 0) {
      sum = nurVal
    } else {
      sum *= nurVal
    }
  })
  return sum / Math.pow(10, decimalLengthSum)
}

/**
 * 除法 divide(0.123 , 1.4567 , 10.56789)
 * @param  {...any} val
 * @returns
 */
export function divide (...val) {
  let sum = 0
  let decimalLengthSum = 0
  val.forEach((x, index) => {
    // 获取当前小数位长度
    const decimalLength = getMaxDecimalLength(x)
    // 将当前数变为整数
    const nurVal = Math.round(x * Math.pow(10, decimalLength))
    if (index === 0) {
      decimalLengthSum = decimalLength
      sum = nurVal
    } else {
      decimalLengthSum -= decimalLength
      sum /= nurVal
    }
  })
  return sum / Math.pow(10, decimalLengthSum)
}

/*
* 获取小数位数
*/
function getMaxDecimalLength (...val) {
  // 最大小数位长度
  let maxDecimalLength = 0
  val.forEach((x) => {
    const strVal = x.toString()
    const dotIndex = strVal.indexOf('.')
    if (dotIndex > -1) {
      // 获取当前值小数位长度
      const curDecimalLength = strVal.length - 1 - dotIndex

      if (curDecimalLength > maxDecimalLength) {
        maxDecimalLength = curDecimalLength
      }
    }
  })
  return maxDecimalLength
}
